package org.groupg.project.configmanager.ui;


import org.groupg.project.configmanager.model.DatabaseConfig;
import org.groupg.project.configmanager.service.ConfigService;
import org.groupg.project.configmanager.util.ClipboardUtil;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.List;

/**
 * 数据库配置面板，显示和管理数据库配置，支持Ctrl+C复制单元格内容
 */
public class DatabaseConfigPanel extends JPanel {
    private JTable configTable;
    private DefaultTableModel tableModel;
    private JButton addButton, editButton, deleteButton, testButton;
    private ConfigService configService;

    /**
     * 构造器，初始化界面和数据
     */
    public DatabaseConfigPanel() {
        configService = new ConfigService();
        initializeUI();
        loadData();
    }

    /**
     * 初始化用户界面
     */
    private void initializeUI() {
        setLayout(new BorderLayout());

        // 创建表格模型和表格
        String[] columnNames = {"ID", "名称", "驱动类", "URL", "用户名","密码"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 表格不可编辑
            }
        };
        configTable = new JTable(tableModel);

        // 设置行高
        configTable.setRowHeight(30);

        // 为表格添加右键复制菜单
        ClipboardUtil.addTableContextMenu(configTable, tableModel);

        // 添加Ctrl+C快捷键支持
        setupCopyShortcut();

        // 添加表格到滚动面板
        add(new JScrollPane(configTable), BorderLayout.CENTER);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout());
        addButton = new JButton("添加");
        editButton = new JButton("编辑");
        deleteButton = new JButton("删除");
        testButton = new JButton("测试连接");

        buttonPanel.add(addButton);
        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(testButton);

        add(buttonPanel, BorderLayout.SOUTH);

        // 添加事件监听器
        addButton.addActionListener(e -> showConfigDialog(null));
        editButton.addActionListener(e -> editSelectedConfig());
        deleteButton.addActionListener(e -> deleteSelectedConfig());
        testButton.addActionListener(e -> testSelectedConnection());
    }

    /**
     * 设置Ctrl+C快捷键复制功能
     */
    private void setupCopyShortcut() {
        // 创建复制操作
        Action copyAction = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                copySelectedCell();
            }
        };

        // 将Ctrl+C绑定到复制操作
        KeyStroke copyKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_DOWN_MASK);
        configTable.getInputMap(JComponent.WHEN_FOCUSED).put(copyKeyStroke, "copy");
        configTable.getActionMap().put("copy", copyAction);

        // 添加工具提示
        configTable.setToolTipText("选中单元格后按 Ctrl+C 复制内容");
    }

    /**
     * 复制选中的单元格内容
     */
    private void copySelectedCell() {
        int selectedRow = configTable.getSelectedRow();
        int selectedColumn = configTable.getSelectedColumn();

        if (selectedRow >= 0 && selectedColumn >= 0) {
            Object value = tableModel.getValueAt(selectedRow, selectedColumn);
            if (value != null) {
                ClipboardUtil.copyToClipboard(value.toString());

                // 显示短暂的复制成功提示
                showCopySuccessTooltip(selectedRow, selectedColumn, value.toString());
            }
        } else {
            // 如果没有选中单元格，尝试复制整行
            copySelectedRow();
        }
    }

    /**
     * 复制选中的整行数据
     */
    private void copySelectedRow() {
        int selectedRow = configTable.getSelectedRow();
        if (selectedRow >= 0) {
            StringBuilder rowData = new StringBuilder();
            for (int col = 0; col < tableModel.getColumnCount(); col++) {
                Object value = tableModel.getValueAt(selectedRow, col);
                rowData.append(tableModel.getColumnName(col)).append(": ").append(value);
                if (col < tableModel.getColumnCount() - 1) {
                    rowData.append("\r");
                }
            }
            ClipboardUtil.copyToClipboard(rowData.toString());
            showCopySuccessTooltip(selectedRow, -1, "整行数据");
        } else {
            // 显示提示信息
            JOptionPane.showMessageDialog(this,
                    "请先选择要复制的单元格或行",
                    "提示",
                    JOptionPane.INFORMATION_MESSAGE);
        }
    }

    /**
     * 显示复制成功的工具提示
     */
    private void showCopySuccessTooltip(int row, int column, String value) {
        // 获取单元格的屏幕位置
        Rectangle cellRect = configTable.getCellRect(row, Math.max(column, 0), false);
        Point location = cellRect.getLocation();
        SwingUtilities.convertPointToScreen(location, configTable);

        // 创建工具提示窗口
        JWindow tooltip = new JWindow();
        tooltip.setAlwaysOnTop(true);

        JLabel label = new JLabel("已复制: " + (value.length() > 20 ? value.substring(0, 20) + "..." : value));
        label.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 5));
        label.setBackground(new Color(240, 240, 240));
        label.setOpaque(true);

        tooltip.getContentPane().add(label);
        tooltip.pack();
        tooltip.setLocation(location.x, location.y - tooltip.getHeight());

        // 显示工具提示
        tooltip.setVisible(true);

        // 2秒后自动隐藏
        Timer timer = new Timer(2000, e -> tooltip.dispose());
        timer.setRepeats(false);
        timer.start();
    }

    /**
     * 加载数据到表格
     */
    private void loadData() {
        try {
            List<DatabaseConfig> configs = configService.getAllDatabaseConfigs();
            tableModel.setRowCount(0); // 清空表格

            for (DatabaseConfig config : configs) {
                tableModel.addRow(new Object[]{
                        config.getId(),
                        config.getName(),
                        config.getDriverClass(),
                        config.getUrl(),
                        config.getUsername(),
                        config.getPassword()
                });
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * 显示配置对话框（添加或编辑）
     *
     * @param config 要编辑的配置，如果为null则添加新配置
     */
    private void showConfigDialog(DatabaseConfig config) {
        DatabaseConfigDialog dialog = new DatabaseConfigDialog((Frame) SwingUtilities.getWindowAncestor(this), config);
        dialog.setVisible(true);
        if (dialog.isSaved()) {
            try {
                configService.saveDatabaseConfig(dialog.getConfig());
                loadData();
                JOptionPane.showMessageDialog(this, "配置保存成功", "成功", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "保存失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    /**
     * 编辑选中的配置
     */
    private void editSelectedConfig() {
        int selectedRow = configTable.getSelectedRow();
        if (selectedRow >= 0) {
            Integer id = (Integer) tableModel.getValueAt(selectedRow, 0);
            try {
                DatabaseConfig config = configService.getDatabaseConfigById(id);
                if (config != null) {
                    showConfigDialog(config);
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "加载配置失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择要编辑的配置", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }

    /**
     * 删除选中的配置
     */
    private void deleteSelectedConfig() {
        int selectedRow = configTable.getSelectedRow();
        if (selectedRow >= 0) {
            int result = JOptionPane.showConfirmDialog(this, "确定要删除选中的配置吗？", "确认删除", JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.YES_OPTION) {
                Integer id = (Integer) tableModel.getValueAt(selectedRow, 0);
                try {
                    configService.deleteDatabaseConfig(id);
                    loadData();
                    JOptionPane.showMessageDialog(this, "删除成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(this, "删除失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择要删除的配置", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }

    /**
     * 测试选中的数据库连接
     */
    private void testSelectedConnection() {
        int selectedRow = configTable.getSelectedRow();
        if (selectedRow >= 0) {
            Integer id = (Integer) tableModel.getValueAt(selectedRow, 0);
            try {
                DatabaseConfig config = configService.getDatabaseConfigById(id);
                if (config != null) {
                    JOptionPane.showMessageDialog(this,
                            "数据库连接测试功能待实现\n配置信息:\n" +
                                    "驱动: " + config.getDriverClass() + "\n" +
                                    "URL: " + config.getUrl() + "\n" +
                                    "用户: " + config.getUsername(),
                            "测试信息",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "加载配置失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择要测试的配置", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }
}